package servlet.ajax;

import dao.GenericDAO;
import dao.impl.GenericDAOImpl;
import entity.User;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

/**
 * Обрабатывает ajax-запросы генерируемые js-приложеннием панели администратора.
 *
 * @author Konstantin Chumachenko <kostyachum@gmail.com>
 */
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        JSONObject json = new JSONObject();
       System.out.println("LoginServlet");
        try {
            GenericDAO<User, Long> daoUser = new GenericDAOImpl<User, Long>(User.class);

            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User user = new User();
            user = daoUser.getUserByName(username);
            System.out.println(username);
            System.out.println(daoUser.getPasswordDigest(password));
            if (user.getDigest().equals(daoUser.getPasswordDigest(password))) {
                request.getSession().setAttribute("username", username);
                System.out.println("Success login!");
                response.sendRedirect("/index?p=admin");
            } else {
                System.out.println("Bad login!");
                json.put("error", "errorLogin");
            }
        } catch (Exception err) {
            err.printStackTrace();
            json.put("error", "big error: " + err.getMessage());
        }
        /*
         * Отправка ответа
         */
        System.out.println(json);
        PrintWriter pw = response.getWriter();
        response.setContentType("text/plain");
        pw.println("" + json.toString() + "");
        pw.flush();
        pw.close();
    }
}
